<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;

class Admin extends Base
{
    protected $type = [
        'last_time' => 'timestamp',
    ];

    protected function role(): object
    {
        return $this->hasOne(Role::class, 'id', 'role_id');
    }

    public static function _save($param, $logs): array
    {
        try {
            if (!empty($param['id'])) {
                if (!empty($param['password'])) {
                    $param['password'] = md5($param['password']);
                } else {
                    unset($param['password']);
                }
                $model = parent::update($param);
                $group = Db::name('auth_group_access')->where(['uid' => $param['id']])->find();
                if ($group['group_id'] != $param['role_id']) {
                    Db::name('auth_group_access')->where(['uid' => $param['id']])->update(['group_id' => $param['role_id']]);
                }
                $model->operation = 'save';
            } else {
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('111111');
                $model = parent::create($param);
                $model->operation = 'create';
                Db::name('auth_group_access')->insert(['uid' => $model->id, 'group_id' => $model->role_id]);
                Logs::adds('后台添加新管理员，账号【' . $model->admin_name . '】');
            }

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '操作成功'];
    }
}